package com.mazaiting.cos

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.os.Environment
import android.support.v7.app.AppCompatActivity
import android.util.Log
import android.view.View
import com.tencent.cos.xml.CosXmlService
import com.tencent.cos.xml.CosXmlServiceConfig
import com.tencent.cos.xml.exception.CosXmlClientException
import com.tencent.cos.xml.exception.CosXmlServiceException
import com.tencent.cos.xml.listener.CosXmlResultListener
import com.tencent.cos.xml.model.CosXmlRequest
import com.tencent.cos.xml.model.CosXmlResult
import com.tencent.cos.xml.model.`object`.GetObjectRequest
import com.tencent.cos.xml.model.`object`.PutObjectRequest
import com.tencent.qcloud.core.auth.ShortTimeCredentialProvider
import kotlinx.android.synthetic.main.activity_main.*


class MainActivity : AppCompatActivity() {
  private val TAG = MainActivity::class.java.simpleName
  /** 对象存储的服务 APPID */
  private val appid = "1256286377"
  /** 存储桶所在的区域 */
  private val regison = "ap-chengdu"
  /** 密钥ID */
  private val secretId = "AKIDvhFdniys77sSntpZ3LOFsGPJyRfeZvBg"
  /** 密钥KEY */
  private val secretKey = "jGYbP0LTLxUs0tWsy60fAQTHp9D2cy5x"
  /** SecretKey有效时间，单位秒 */
  private val keyDuration = 600L
  private lateinit var cosXmlService: CosXmlService
  
  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    
    // 创建CosXmlServiceConfig对象，根据需要修改默认的配置参数
    val serviceConfig = CosXmlServiceConfig
            .Builder()
            .setAppidAndRegion(appid, regison)
            .setDebuggable(true)
            .builder()
    
    // 创建获取签名类
    val localCredentialProvider = ShortTimeCredentialProvider(secretId, secretKey, keyDuration)
    cosXmlService = CosXmlService(applicationContext, serviceConfig, localCredentialProvider)
    
    // 上传
    btn_upload.setOnClickListener { v: View? ->
      Thread(Runnable {
        //        uploadSync()
        uploadAsync()
      }).start()
    }
    // 下载
    btn_download.setOnClickListener { v: View? ->
      Thread(Runnable {
        download()
      }).start()
    }
  }
  
  /**
   * 下载
   */
  private fun download() {
    // 对象存储桶名称
    val bucket = "test-$appid"
    // 文件路径
    val cosPath = "huihe.apk"
    // 签名的有效期，单位为秒
    val signDuration = 600L
    // 待上传文件路径
    val srcPath = "${Environment.getExternalStorageDirectory()}/huihe/"
    // 获取请求
    val getObjectRequest = GetObjectRequest(bucket, cosPath, srcPath)
    // 设置签名
    getObjectRequest.setSign(signDuration, null, null)
    // 设置进度显示
    getObjectRequest.setProgressListener { progress, max ->
      val result = (progress * 100.0 / max)
      Log.e(TAG, "progress = $result %")
    }
    //使用同步方法下载
    try {
      val getObjectResult = cosXmlService.getObject(getObjectRequest)
      Log.e(TAG, "success：${getObjectResult.javaClass}")
      runOnUiThread({startInstallActivity(applicationContext, "$srcPath$cosPath")})
    } catch (e: CosXmlClientException) {
      Log.e(TAG, "CosXmlClientException = " + e.toString())
    } catch (e: CosXmlServiceException) {
      Log.e(TAG, "CosXmlServiceException = " + e.toString())
    }

    //**使用异步回调请求**
    /**
    
    cosXmlService.getObjectAsync(getObjectRequest, new CosXmlResultListener() {
    @Override
    public void onSuccess(CosXmlRequest cosXmlRequest, CosXmlResult cosXmlResult) {
    Log.w("TEST","success");
    }
    
    @Override
    public void onFail(CosXmlRequest cosXmlRequest, CosXmlClientException clientException, CosXmlServiceException serviceException)  {
    String errorMsg = clientException != null ? clientException.toString() : serviceException.toString();
    Log.w("TEST",errorMsg);
    }
    });*/
    
  }
  
  /**
   * 同步上传
   */
  private fun uploadAsync() {
    // 对象存储桶名称
    val bucket = "test-$appid"
    // 文件名称
    val cosPath = "huihe.apk"
    // 待上传文件路径
    val srcPath = "${Environment.getExternalStorageDirectory()}/huihe.apk"
    // 签名的有效期，单位为秒
    val signDuration = 600L
    // 创建上传对象
    val putObjectRequest = PutObjectRequest(bucket, cosPath, srcPath)
    // 设置签名，若不调用，默认为60s
    putObjectRequest.setSign(signDuration, null, null)
    // 设置进度显示
    putObjectRequest.setProgressListener({ progress, max ->
      val result = (progress * 100.0 / max)
      Log.e(TAG, "progress = $result %")
    })
    // 异步上传
    cosXmlService.putObjectAsync(putObjectRequest, object : CosXmlResultListener {
      override fun onSuccess(putObjectRequest: CosXmlRequest?, result: CosXmlResult?) {
        if (result != null) {
          Log.e(TAG, "success = + ${result.accessUrl}")
        }
      }
      
      override fun onFail(p0: CosXmlRequest?, clientException: CosXmlClientException?, serviceException: CosXmlServiceException?) {
        val errorMsg = clientException?.toString() ?: serviceException.toString()
        Log.e(TAG, errorMsg)
      }
      
    })
  }
  
  /**
   * 同步上传
   */
  private fun uploadSync() {
    // 对象存储桶名称
    val bucket = "test-$appid"
    // 文件名称
    val cosPath = "huihe.apk"
    // 待上传文件路径
    val srcPath = "${Environment.getExternalStorageDirectory()}/huihe.apk"
    // 签名的有效期，单位为秒
    val signDuration = 600L
    // 创建上传对象
    val putObjectRequest = PutObjectRequest(bucket, cosPath, srcPath)
    // 设置签名，若不调用，默认为60s
    putObjectRequest.setSign(signDuration, null, null)
    // 设置进度显示
    putObjectRequest.setProgressListener({ progress, max ->
      val result = (progress * 100.0 / max)
      Log.e(TAG, "progress = $result %")
    })
    
    try {
      // 同步上传
      val putObjectResult = cosXmlService.putObject(putObjectRequest)
      Log.e(TAG, "success: ${putObjectResult.accessUrl}")
    } catch (e: CosXmlClientException) {
      //抛出异常
      Log.e(TAG, "CosXmlClientException = ${e.message}")
    } catch (e: CosXmlServiceException) {
      //抛出异常
      Log.e(TAG, "CosXmlServiceException = ${e.message}")
    }
  }
  
  /**
   * 安装应用
   */
  private fun startInstallActivity(context :Context, path :String) {
    val install = Intent(Intent.ACTION_VIEW)
    install.setDataAndType(Uri.parse("file://" + path), "application/vnd.android.package-archive")
    install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
    context.startActivity(install)
  }
}

















